<?php
namespace app\pay\controller\common;

use think\Controller;

class DaifuQuery extends Controller {
    /*
     * 客户向畅远管理后台发起代付申请
     * 将申请信息保存到model('PayBisApply')
     */
    public function index() {
        $data = input('post.');
        if(array_key_exists('merchant_id', $data)) {
            $merchantId = $data['merchant_id'];
        } else {
            return retMsgFalse('缺少商户号');
        }
        // 根据商户号获取商户相关信息
        $resPayBis = model('PayBis')->get(['merchant_id' => $merchantId]);
        if($resPayBis) {
            if(array_key_exists('mchnt_batchid', $data)) {
                $mchntBatchid = $data['mchnt_batchid'];   // 出款批次号
            } else {
                $mchntBatchid = null;
            }

            if(array_key_exists('mchnt_orderid', $data)) {
                $mchntOrderId = $data['mchnt_orderid']; // 商户订单号  
            } else {
                $mchntOrderId = null;
            }

            if($mchntBatchid == null && $mchntOrderId == null) {
                return retMsgFalse('缺少订单号');
            }
      
            if($mchntBatchid != null) {
                $resPayDaifuApply = model('PayDaifuApply')->get(['mchnt_batchid' => $mchntBatchid]);
            } else {
                $resPayDaifuApply = model('PayDaifuApply')->get(['mchnt_orderid' => $mchntOrderId]);
            }

            if($resPayDaifuApply) {
                $res = $this->queryHandle($data, $resPayBis, $resPayDaifuApply);
                return $res;
            } else {
                return orderidFalse(); // 订单号不存在
            }
        } else {
            // 商户号不存在
            return paymchntIdFalse();
        }  
    }
    
    /*
     * 验证签名并保存数据到数据库
     */
    private function queryHandle($data, $resPayBis, $resPayDaifuApply) {
        $verSign = $data['signature'];
        unset($data['signature']);
        $md5key = $resPayBis->md5key;
        $data['signature'] = payChangyuanSign($data, $md5key); // 创建签名
        
        // 验证签名
        if($verSign == $data['signature']) {
            $dataArr = array(
                'merchant_id'     => $resPayDaifuApply->merchant_id,
                'mchnt_batchid'   => $resPayDaifuApply->mchnt_batchid,
                'mchnt_orderid'   => $resPayDaifuApply->mchnt_orderid,
                'status'          => $resPayDaifuApply->status,
                'bank_status'     => $resPayDaifuApply->bank_status,
                'is_notice'       => $resPayDaifuApply->is_notice,
                'msg'             => $resPayDaifuApply->remark
            );
            return daifuQueryTrue($dataArr, $resPayBis->md5key); 
        } else {
            // <畅远>签名验证失败
            return changyuanSignFalse();
        } 
    }
}

